import { http } from "@/utils/http";

type Result = {
  success: boolean;
  data: any;
};

type ResultTable = {
  success: boolean;
  data?: {
    /** 列表数据 */
    data: Array<any>;
    /** 总条目数 */
    total?: number;
    /** 每页显示条目个数 */
    per_page?: number;
    /** 当前页数 */
    current_page?: number;
    /** 搜索条件配置 */
    search_cond_arr?: Array<any>;
    /** 订单状态配置 */
    order_status_arr?: Array<any>;
  };
};

/**
 * 马帮订单管理 - 获取订单列表
 */
export const mabangOrderIndex = (data?: object, method?: 'get') => {
  let path = getnewUrl("/mabang-orders", data, method);
  return http.request<ResultTable>(method, path, { data });
};

/**
 * 马帮订单管理 - 获取订单详情
 */
export const mabangOrderShow = (id: string | number) => {
  return http.request<Result>("get", `/mabang-orders/${id}`);
};

/**
 * 马帮订单管理 - 获取订单详情（详细信息）
 */
export const mabangOrderDetail = (id: string | number) => {
  return http.request<Result>("get", `/mabang-orders/${id}`);
};

/**
 * 马帮订单数据捕获 - 保存订单数据
 */
export const mabangOrderSave = (data: object) => {
  return http.request<Result>("post", "/mabang-order/save", { data });
};

/**
 * 拼装新的方法
 * @param path
 * @param data
 * @param method
 */
function getnewUrl(path, data?: any, method?: 'get') {
  if (method == undefined) method = 'get';
  
  if ((method as string) == 'put' || (method as string) == 'delete') {
    path = path + '/' + data?.id;
  } else if (method == 'get' && data !== undefined) {
    const removeEmpty = obj => Object.keys(obj)
      .filter(key => obj[key] !== undefined && obj[key] !== null && obj[key] !== '')
      .reduce((acc, key) => {
        acc[key] = obj[key];
        return acc;
      }, {});
    
    data = removeEmpty(data);
    const query = new URLSearchParams(data as any).toString();
    path = `${path}?${query}`;
  }

  return path;
} 